<template>
  <div class="statistics-filter" v-if="formAnalysis">
    <div class="download-btn">
      <el-button @click="showExport = true" style="margin-bottom: 10px">导出供应商</el-button>
    </div>
    <RuifoxTable v-model:tableData="formAnalysis.list.formAnalysisData" v-model:fieldList="fieldList" :tableProps="{
        labelKey: 'label',
        valueKey: 'key'}">
      <template #status="{element}">{{element.status == 0 ? '待审核':(element.status == 1 ? '已通过' : '未通过')}}</template>
      <template #[item.prop]="{element}" v-for="(item, index) in formAnalysis.formAnalysisProp" :key="index">
        <template v-if="item.prop.includes('fileUpload') || item.prop.includes('imgUpload')">
          <div class="file-box">
            <span class="file" :title="file.fileName" v-for="(file, fileIndex) in element[item.prop]" :key="fileIndex" @click="downLoadFile(file)">{{file.fileName}}</span>
          </div>
        </template>
      </template>
      <template #options="{element}">
        <div class="table-td-option">
          <el-button type="primary" size="small" class="unmover" link @click="goAnswerDetail(element)">详情</el-button>
          <el-button type="primary" size="small" class="unmover" link @click="goVendorDetail(element, 1)">查看供应商</el-button>
          <!-- <el-button type="primary" size="small" class="unmover" link @click="deleteAnswer(element)">删除</el-button> -->
          <el-dropdown>
            <span class="el-dropdown-link unmover">
              <i class="iconfont">&#xe78d;</i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleAnswerAudit(element,1)">标记为通过</el-dropdown-item>
                <el-dropdown-item @click="handleAnswerAudit(element,2)">标记为未通过</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>
    </RuifoxTable>
    <slot name="footer-pagenation"></slot>
    <el-dialog v-if="answerDetailOpen" v-model="answerDetailOpen" title="答卷详情" align-center width="800px">
      <div class="preview-form" v-loading="answerDetailLoading">
        <div class="publish-info">
          <div>
            <span class="label">序号：</span>
            <span>{{curRow.index}}</span>
          </div>
          <div>
            <span class="label">答卷状态：</span>
            <span :style="{'color': filterAnswerStatus(curRow.status).color}">{{filterAnswerStatus(curRow.status).label}}</span>
          </div>
          <div>
            <span class="label">答卷提交时间：</span>
            <span>{{curRow.answerTime}}</span>
          </div>
          <el-button size="small" @click="handleAnswerAudit(curRow, 1)" type="primary">通过</el-button>
          <el-button size="small" @click="handleAnswerAudit(curRow, 2)" type>不通过</el-button>
        </div>
        <el-scrollbar max-height="70vh" v-if="!answerDetailLoading">
          <form-viewer :formInfo="answerDetail"></form-viewer>
        </el-scrollbar>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="preAnswerDetail" :disabled="curRowIndex <= 0">上一份报名</el-button>
          <el-button type @click="nextAnswerDetail" :disabled="curRowIndex >= formAnalysis.list.formAnalysisData.length - 1">下一份报名</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 查看供应商 -->
    <el-drawer v-model="detailsDrawer" title="会员信息概览" size="800px">
      <!-- <supplierDetails v-if="detailsDrawer" :curRow="supplierRow" :curBtnType="curBtnType" /> -->
      <template #footer>
        <div style="flex: auto">
          <template v-if="curBtnType == 2">
            <el-button v-if="supplierRow.isBan == 1" type="danger" @click="handleVendorEdit('isBan', 2, supplierRow)">禁用</el-button>
            <el-button v-else type @click="handleVendorEdit('isBan', 1, supplierRow)">启用</el-button>
          </template>
          <el-button @click="detailsDrawer = false">取消</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 下载报告 -->
    <el-dialog v-model="showExport" title="导出" width="30%" align-center :inline="true">
      <el-form label-width="230px" label-position="left">
        <el-form-item label="是否导出当前图表所展示的数据?">
          <el-radio-group v-model="exportType">
            <el-radio label="0" size="small" style="margin-right: 10px">excel</el-radio>
            <el-radio label="1" size="small" style="margin-right: 10px">zip</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showExport = false">取消</el-button>
          <el-button type="primary" @click="downLoadReport">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, computed } from 'vue'
import { getAnswerDetail, deleteAnswerByIds, answerAudit, getFormAnalysisData, getFormStatistics } from '@/api/formDesign'
// import { fileSecretKey } from '@/views/formSystem/formDesign/config/formCmpConfig.js'
import { ElMessageBox, ElMessage } from 'element-plus'
// import formViewer from '@/views/formSystem/formDesign/formPreview/formPreview.vue'
import { useRouter } from 'vue-router'
// import supplierDetails from '@/views/bidding/manage/supplierManage/components/supplierDetails.vue'
// import { export2ExcelWithLinks, exportWordZip } from '@/utils/export.js'

const fieldList = ref([])

const router = useRouter()

const props = defineProps({
  formAnalysis: {
    type: Object,
  },
  formAnalysisParams: {
    type: Object,
  },
  formId: {
    type: [String, Number],
  },
  isBidding: {
    type: Boolean,
    default: false,
  },
})
const emits = defineEmits(['refreshData'])
const curFormId = ref(router.currentRoute.value.query.formId || props.formId)
const formAnalysis = computed(() => {
  return props.formAnalysis
})
setTimeout(() => {
  fieldList.value.push({
    label: '状态',
    key: 'status',
    width: 100,
  })
  fieldList.value.push(
    ...formAnalysis.value.formAnalysisProp.map((item) => {
      return {
        label: item.label,
        key: item.prop,
        minWidth: 120,
        showTextTip: true,
      }
    })
  )
  fieldList.value.push({
    label: '操作',
    width: 240,
    fixed: 'right',
    key: 'options',
  })
}, 100)
const answerDetailOpen = ref(false)
const answerDetail = ref()
const answerDetailLoading = ref()
const curRow = ref()
const curRowIndex = ref()
// 查看详情
const goAnswerDetail = async (row) => {
  curRow.value = row
  curRowIndex.value = formAnalysis.value.list.formAnalysisData.findIndex((item) => item.id == curRow.value.id)
  answerDetailLoading.value = true
  let res = await getAnswerDetail({ id: row.id, formId: curFormId.value })
  answerDetail.value = res.data
  answerDetailLoading.value = false
  answerDetailOpen.value = true
}
// 查看供应商
const detailsDrawer = ref(false)
const curBtnType = ref(1) //1 查看 2 审核 3 拉黑

//查看 审核 拉黑
const supplierRow = ref({})
const goVendorDetail = (ele, type) => {
  supplierRow.value = structuredClone(ele)
  supplierRow.value.id = ele.member_id
  curBtnType.value = type
  detailsDrawer.value = true
}
// const goVendorDetail = (val) => {
//   console.log('val',val.member_id);
// }
// 上一份
const preAnswerDetail = () => {
  curRow.value = formAnalysis.value.list.formAnalysisData[curRowIndex.value - 1]
  goAnswerDetail(curRow.value)
}
// 下一份
const nextAnswerDetail = () => {
  curRow.value = formAnalysis.value.list.formAnalysisData[curRowIndex.value + 1]
  goAnswerDetail(curRow.value)
}
const answerStatusOption = ref([
  { label: '待审核', value: 0, color: '#333' },
  { label: '已通过', value: 1, color: 'green' },
  { label: '未通过', value: 2, color: 'red' },
])
const filterAnswerStatus = (status) => {
  return answerStatusOption.value.find((item) => item.value == status)
}
// 答卷审核
const handleAnswerAudit = async (row, status) => {
  let res = await answerAudit({ id: row.id, status, formId: curFormId.value })
  row.status = status
  if (res.code == 20000) {
    ElMessage({
      showClose: true,
      message: '操作成功',
      type: 'success',
    })
  }
  emits('refreshData')
}
// 删除
const deleteAnswer = (row) => {
  let ids = []
  if (row) {
    ids = [row.id]
  }
  ElMessageBox.confirm(
    '<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除答卷？</p><span style="font-size: 14px;color: #FF5240;">清除后内容将无法恢复</span></div>',
    '删除确认',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    }
  ).then(async () => {
    let res = await deleteAnswerByIds({ ids, formId: curFormId.value })
    if (res.code == 20000) {
      ElMessage({
        showClose: true,
        message: '删除成功',
        type: 'success',
      })
      emits('refreshData')
    }
  })
}
deleteAnswer

// 下载报告
const qsStatusOption = ref([
  //状态字体和按钮样式
  { label: '全部', value: 100 },
  { label: '待审核', value: 0, backgroudColor: '#ee7755', color: '#2CBF77' },
  { label: '审核中', value: 1, backgroudColor: '#ee7755', color: '#2CBF77' },
  { label: '已发布', value: 2, backgroudColor: '#2CBF77', color: '#2CBF77' },
  { label: '未通过', value: 3, backgroudColor: '#F00', color: '#2CBF77' },
  { label: '已下线', value: 4, backgroudColor: '#AAAAAA', color: '#FF9700' },
  { label: '即将下线', value: 51, backgroudColor: '#FF9700', color: '#FF9700' },
])

const formReport = ref({})
const formReportLoading = ref(false)
// 获取统计报表
const handleGetFormReport = async () => {
  formReportLoading.value = true
  // let params = props.formAnalysisParams
  let res = await getFormStatistics(props.formAnalysisParams)
  let curObj = qsStatusOption.value.find((item) => item.value == res.data.status)
  formReport.value = { ...res.data, statusInfo: curObj } //处理得到当前表单状态信息
  formReportLoading.value = false
}
handleGetFormReport()

const showExport = ref(false)
const exportType = ref()
const downLoadReport = async () => {
  let params = props.formAnalysisParams
  let res = await getFormAnalysisData(params)
  if (res.code == 20000) {
    let headerProperties = {}
    res.data.formAnalysisProp.forEach((item) => {
      if (item.prop.indexOf('secondTitle') === -1) {
        headerProperties[item.prop] = item.label
      }
    })
    // if (exportType.value === '0') {
    //   export2ExcelWithLinks(res.data.list.formAnalysisData, headerProperties, ['fileUpload', 'imgUpload'], new Date().getTime() + '.xlsx')
    // } else {
    //   const fileData = addQuestionAndResult(res.data.list.formAnalysisData, headerProperties)
    //   exportWordZip(fileData, formReport.value.title)
    // }
    showExport.value = false
  }
}
//word数据处理
// function addQuestionAndResult(data, questions) {
//   return data.map((obj) => {
//     let genFolder = false //是否创建文件夹
//     const questionAndResult = []
//     for (const prop in obj) {
//       if (
//         !['index', 'answerTime', 'resource', 'ip'].includes(prop) &&
//         // questions.hasOwnProperty(prop)
//         Object.prototype.hasOwnProperty.call(questions, prop)
//       ) {
//         let question = questions[prop]
//         let result = obj[prop]
//         let hasFile = false //是否有文件
//         if (prop.includes('Upload')) {
//           result.forEach(async (item) => (item.url += fileSecretKey))
//           hasFile = true
//           genFolder = true
//         }
//         questionAndResult.push({ question, result, hasFile })
//       }
//     }

//     // 根据 question 中属性值的序号排序
//     questionAndResult.sort((a, b) => {
//       const indexA = parseInt(a.question.split('、')[0])
//       const indexB = parseInt(b.question.split('、')[0])
//       return indexA - indexB
//     })

//     return { ...obj, questionAndResult, genFolder }
//   })
// }

// 下载附件
const downLoadFile = (file) => {
  file
  // window.open(file.url + fileSecretKey)
}
</script>
<style scoped lang='scss'>
.statistics-filter {
  width: 100%;
  // margin-top: 20px;
  .download-btn {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
  .file-box {
    display: flex;
    flex-direction: column;
    .file {
      margin-right: 10px;
      color: $mainColor;
      cursor: pointer;
      &:hover {
        text-decoration: underline;
      }
    }
  }
}
.btns {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .more-icon {
    cursor: pointer;
    font-size: 22px;
    margin-left: 10px;
    color: $mainColor;
  }
}
.preview-form {
  min-height: 700px;
  .publish-info {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    div {
      margin-right: 40px;
      .label {
        color: #999;
      }
    }
  }
}
</style>